package query;

import global.Minibase;
import global.RID;
import global.SearchKey;
import heap.HeapFile;
import heap.HeapScan;

import index.HashIndex;

import parser.AST_CreateIndex;
import relop.Schema;
import relop.Tuple;

/**
 * Execution plan for creating indexes.
 */
class CreateIndex implements Plan {

	/**
	 * Optimizes the plan, given the parsed query.
	 * 
	 * @throws QueryException if index already exists or table/column invalid
	 */
	/** Name of the index to create. */
	protected String name_index;
	protected String name_table;
	protected String name_column;
	protected HashIndex h;

	/** Schema of the table to create. */
	protected Schema schema;

	public CreateIndex(AST_CreateIndex tree) throws QueryException {
		name_index = tree.getFileName();
		System.out.println ("name_index = "+ name_index);
		QueryCheck.fileNotExists(name_index);
		name_table = tree.getIxTable();
		QueryCheck.tableExists(name_table);
		
		schema = Minibase.SystemCatalog.getSchema(name_table);
		name_column = tree.getIxColumn();
		QueryCheck.columnExists(schema, name_column);
		h = new HashIndex(name_index);
	} // public CreateIndex(AST_CreateIndex tree) throws QueryException

	/**
	 * Executes the plan and prints applicable output.
	 */
	public void execute() {
		//TODO: Check if this hm method is correct
		
		Minibase.SystemCatalog.createIndex(name_index, name_table, name_column);
		
		//TODO:: shahul ... if table already has some entires, scan that and put in hashIndex
		HeapScan hs = new HeapFile (name_table).openScan();
		RID r = new RID();
		
		while (hs.hasNext()){
			byte []b = hs.getNext(r);
			Tuple t = new Tuple (schema, b);
			SearchKey sk = new SearchKey (t.getField(name_column));
			h.insertEntry(sk, r);
		}

		// print the output message
		System.out.println("Index created ");
		hs.close();

	} // public void execute()

} // class CreateIndex implements Plan
